﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

using ELTE.SEM.Data;
using System.IO;
using ELTE.SEM.Common;
using ELTE.SEM.Data.ViewModels;
using ELTE.SEM.Data.Managers;

namespace ELTE.NPRG.WEB.Controllers
{
    public class ControllerBase : Controller
    {
        protected SemDataEntities DataEntities { get; set; }
        protected ConfigHelper ConfigHelper { get; set; }

        public ControllerBase()
            : base()
        {
            DataEntities = new SEM.Data.SemDataEntities();
            ConfigHelper = new ConfigHelper();
        }

        public ControllerBase(SemDataEntities entities)
            : base()
        {
            DataEntities = entities;
            ConfigHelper = new ConfigHelper();
        }

        public string RenderViewToString(string viewName, object model)
        {
            ViewData.Model = model;
            using (var sw = new StringWriter())
            {
                var viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);
                var viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);
                viewResult.View.Render(viewContext, sw);
                viewResult.ViewEngine.ReleaseView(ControllerContext, viewResult.View);
                return sw.GetStringBuilder().ToString();
            }
        }

        [HttpGet]
        public JsonResult GetView(string viewName)
        {
            if (!String.IsNullOrEmpty(viewName))
            {
                return Json(RenderViewToString(viewName, null), JsonRequestBehavior.AllowGet);
            }
            else
            {
                return Json(null, JsonRequestBehavior.AllowGet);
            }
        }

        protected SemFileServerLoginViewModel GetRemoteLoginViewModel()
        {
            SemFileServerLoginViewModel loginViewModel = new SemFileServerLoginViewModel
            {
                Server = ConfigHelper.Value("SemFileServer"),
                UserName = ConfigHelper.Value("SemFileUserName"),
                Password = ConfigHelper.Value("SemFilePassword"),
                HomeFolder = ConfigHelper.Value("SemFileHomePath"),
            };
            return loginViewModel;
        }
    }
}
